<script setup lang="ts">
import { request } from '@/api';
import { closeToast, showLoadingToast, showSuccessToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import b64toBlob from 'b64-to-blob'

//创建修改头像的变量
const showAvatarSheet = ref(false);
//创建修改头像选项列表
const showAvatarActions = [
      { name: '点击拍照' },
      { name: '从相册选取' },
    ];
//点击拍照或从相册选取的回调函数
const  onSelect =async (action: ActionSheetAction, index: number)=>{
  if(index === 0){
      const data = await mk.pickerCamera();
      await onUpdateAvatar(data)
  }else if(index === 1){
      const data = await mk.pickerPhoto()
      await onUpdateAvatar(data)
  }
}

//传入获取到的图片进行修改头像
const onUpdateAvatar = async (data:string) => {
  try {
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    //1. 将获取到的图片从base64字符串转为二进制流数据
    const image = b64toBlob(data,'image/jpeg');
    //2. 创建一个fromData对象,用来保存图片数据
    const fd = new FormData();
    //3. 将数据添加到fd对象中
    fd.append('file', image, Date.now() + '.jpeg');
    //4.发送请求修改头像
    const res = await request.post<MkResponse<{avatar:string}>>('member/profile/avatar',fd)
    //5.将头像地址赋值给profile.avatar
    profile.value.avatar = res.data.result.avatar
    //6.同步数据至鸿蒙端
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (error) {
    showToast({ message: '上传失败' })
  }
}

//生日选择弹窗显隐
const showBirthdayPopup = ref(false);
//生日日期选择
const minDate = new Date(1945,10, 1);
const maxDate = new Date();
const currentBrithdayDate = ref(['2002','11','10']);
//点击完成时执行
const onChangeBirthday = (date: Date) => {
  showBirthdayPopup.value = false;
  profile.value.birthday = currentBrithdayDate.value.join('-');
}

//点击地区选择弹窗显隐
const showLocationPopup = ref(false);
//地区数据
const areaList = ref<AreaColumns>();
//获取地区数据
onMounted(async() => {
  const data = await mk.getAreaColumns();
  areaList.value = data;
})
//点击确定执行逻辑
const onSelectedLocation = (area:{selectedValues:number[]}) => {
  showLocationPopup.value = false;
  //赋值
  profile.value.provinceCode = area.selectedValues[0];
  profile.value.cityCode = area.selectedValues[1];
  profile.value.countyCode = area.selectedValues[2];

  //获取省市区选中的数据
  const province = areaList.value?.province_list[area.selectedValues[0]]
  const city = areaList.value?.city_list[area.selectedValues[1]]
  const county = areaList.value?.county_list[area.selectedValues[2]]
  
  profile.value.fullLocation = `${province} ${city} ${county}`
}

//职业选择弹窗显隐
const showProfessionPopup = ref(false);


//获取用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async() => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
    //主动关闭loading效果
    closeToast();
    profile.value = res.data.result
    //将获取到的生日在点开生日选择器时自动定位
    currentBrithdayDate.value = res.data.result.birthday.split('-')
})

const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]

const onChangeProfession = (data: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  console.log(data.selectedValues)
  profile.value.profession  = data.selectedValues[0]
}

//点击保存资料
const loading = ref(false)
const submit = async () => {
  loading.value = true
  //TODO:提交数据
  //发送请求
  const res = await request.put<MkResponse<ProfileInfo>>('member/profile',profile.value)
    console.log(res.data.result)
    mk.updateUser(res.data.result)
    showSuccessToast('保存成功')
    loading.value = false
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <van-action-sheet
    style="padding-bottom: 20px;"
  v-model:show="showAvatarSheet"
  :actions="showAvatarActions"
  cancel-text="取消"
  close-on-click-action
  @select="onSelect"
/>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender"  :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field v-model="profile.birthday"  @click="showBirthdayPopup = true" label="生日" readonly placeholder="请选择日期"></van-field>
      <van-popup
          v-model:show="showBirthdayPopup"
          position="bottom"
          > <van-date-picker @confirm="onChangeBirthday"
          @cancel="showBirthdayPopup = false"
            v-model="currentBrithdayDate"
            title="选择日期"
            :min-date="minDate"
            :max-date="maxDate"
          /></van-popup>
      <van-field v-model="profile.fullLocation"  @click="showLocationPopup = true" label="所在地" readonly placeholder="请选择所在地"></van-field>
      <van-popup v-model:show="showLocationPopup" position="bottom" :style="{ height: '30%' }">
        <van-area @confirm="onSelectedLocation" :area-list="areaList" @cancel="showLocationPopup = false" />
      </van-popup>
    
      <van-field @click="showProfessionPopup = true" v-model="profile.profession"  label="职业" readonly placeholder="请选择职业"></van-field>
      <van-popup v-model:show="showProfessionPopup" round position="bottom">
  <van-picker :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
</van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button :loading="loading" @click="submit" round block type="primary">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>